const TOKEN_KEY = 'student_token'
const REFRESH_TOKEN_KEY = 'student_refresh_token'
const USER_INFO_KEY = 'student_user_info'
const PERMISSIONS_KEY = 'student_permissions'
const SETTINGS_KEY = 'student_settings'

/**
 * 获取token
 */
export function getToken() {
  return localStorage.getItem(TOKEN_KEY)
}

/**
 * 设置token
 */
export function setToken(token) {
  localStorage.setItem(TOKEN_KEY, token)
}

/**
 * 移除token
 */
export function removeToken() {
  localStorage.removeItem(TOKEN_KEY)
  localStorage.removeItem(REFRESH_TOKEN_KEY)
  localStorage.removeItem(USER_INFO_KEY)
  localStorage.removeItem(PERMISSIONS_KEY)
}

/**
 * 获取刷新token
 */
export function getRefreshToken() {
  return localStorage.getItem(REFRESH_TOKEN_KEY)
}

/**
 * 设置刷新token
 */
export function setRefreshToken(refreshToken) {
  localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken)
}

/**
 * 检查是否已登录
 */
export function isLoggedIn() {
  const token = getToken()
  if (!token) return false
  
  // 检查token是否过期
  try {
    const payload = parseJWT(token)
    const currentTime = Math.floor(Date.now() / 1000)
    return payload.exp > currentTime
  } catch (error) {
    console.error('Token解析失败:', error)
    return false
  }
}

/**
 * 解析JWT token
 */
export function parseJWT(token) {
  try {
    const base64Url = token.split('.')[1]
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
        .join('')
    )
    return JSON.parse(jsonPayload)
  } catch (error) {
    throw new Error('Invalid token format')
  }
}

/**
 * 检查token是否即将过期（30分钟内）
 */
export function isTokenExpiringSoon() {
  const token = getToken()
  if (!token) return true
  
  try {
    const payload = parseJWT(token)
    const currentTime = Math.floor(Date.now() / 1000)
    const timeUntilExpiry = payload.exp - currentTime
    return timeUntilExpiry < 30 * 60 // 30分钟
  } catch (error) {
    return true
  }
}

/**
 * 获取token剩余时间（秒）
 */
export function getTokenRemainingTime() {
  const token = getToken()
  if (!token) return 0
  
  try {
    const payload = parseJWT(token)
    const currentTime = Math.floor(Date.now() / 1000)
    return Math.max(0, payload.exp - currentTime)
  } catch (error) {
    return 0
  }
}

/**
 * 获取用户信息
 */
export function getUserInfo() {
  const userInfo = localStorage.getItem(USER_INFO_KEY)
  return userInfo ? JSON.parse(userInfo) : null
}

/**
 * 设置用户信息
 */
export function setUserInfo(userInfo) {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
}

/**
 * 获取用户权限
 */
export function getPermissions() {
  const permissions = localStorage.getItem(PERMISSIONS_KEY)
  return permissions ? JSON.parse(permissions) : []
}

/**
 * 设置用户权限
 */
export function setPermissions(permissions) {
  localStorage.setItem(PERMISSIONS_KEY, JSON.stringify(permissions))
}

/**
 * 检查是否有指定权限
 */
export function hasPermission(permission) {
  const permissions = getPermissions()
  return permissions.includes(permission)
}

/**
 * 检查是否有任一权限
 */
export function hasAnyPermission(permissionList) {
  const permissions = getPermissions()
  return permissionList.some(permission => permissions.includes(permission))
}

/**
 * 检查是否有所有权限
 */
export function hasAllPermissions(permissionList) {
  const permissions = getPermissions()
  return permissionList.every(permission => permissions.includes(permission))
}

/**
 * 格式化权限列表
 */
export function formatPermissions(permissions) {
  if (!Array.isArray(permissions)) return []
  
  return permissions.map(permission => {
    if (typeof permission === 'string') {
      return permission
    }
    if (typeof permission === 'object' && permission.code) {
      return permission.code
    }
    return null
  }).filter(Boolean)
}

/**
 * 获取用户设置
 */
export function getUserSettings() {
  const settings = localStorage.getItem(SETTINGS_KEY)
  return settings ? JSON.parse(settings) : {
    theme: 'light',
    language: 'zh-CN',
    notifications: true,
    autoPlay: true,
    playbackRate: 1.0
  }
}

/**
 * 设置用户设置
 */
export function setUserSettings(settings) {
  const currentSettings = getUserSettings()
  const newSettings = { ...currentSettings, ...settings }
  localStorage.setItem(SETTINGS_KEY, JSON.stringify(newSettings))
}

/**
 * 清除所有本地存储
 */
export function clearStorage() {
  localStorage.removeItem(TOKEN_KEY)
  localStorage.removeItem(REFRESH_TOKEN_KEY)
  localStorage.removeItem(USER_INFO_KEY)
  localStorage.removeItem(PERMISSIONS_KEY)
  localStorage.removeItem(SETTINGS_KEY)
}

/**
 * 检查是否为学生角色
 */
export function isStudent() {
  const userInfo = getUserInfo()
  return userInfo && userInfo.role === 'student'
}

/**
 * 获取学生ID
 */
export function getStudentId() {
  const userInfo = getUserInfo()
  return userInfo ? userInfo.studentId || userInfo.id : null
}

/**
 * 获取学生班级信息
 */
export function getClassInfo() {
  const userInfo = getUserInfo()
  return userInfo ? userInfo.classInfo : null
}

/**
 * 检查是否有课程访问权限
 */
export function hasCourseAccess(courseId) {
  const userInfo = getUserInfo()
  if (!userInfo || !userInfo.enrolledCourses) return false
  
  return userInfo.enrolledCourses.some(course => 
    course.id === courseId || course.courseId === courseId
  )
}

/**
 * 获取已注册课程列表
 */
export function getEnrolledCourses() {
  const userInfo = getUserInfo()
  return userInfo ? userInfo.enrolledCourses || [] : []
}

/**
 * 检查课程是否已过期
 */
export function isCourseExpired(course) {
  if (!course.endTime) return false
  return new Date(course.endTime) < new Date()
}

/**
 * 获取学习进度
 */
export function getLearningProgress(courseId) {
  const userInfo = getUserInfo()
  if (!userInfo || !userInfo.learningProgress) return 0
  
  const progress = userInfo.learningProgress.find(p => p.courseId === courseId)
  return progress ? progress.percentage : 0
}